using System;
using System.IO;
using System.Collections.Generic;
using Servlets.Exceptions;
using Servlets.Api;

namespace Servlets.Http
{
	public class HttpResponse : IResponse
	{
		public HttpStatus HttpStatus{get;set;}
		
		private Dictionary<HttpProperty, string> properties = new Dictionary<HttpProperty, string>();
		public IEnumerable<HttpProperty> AllProperties {get{return properties.Keys;}}
		
		private ResponseStream outputStream;
		public ResponseStream OutputStream{get{return outputStream;}}
		
		public HttpVersion HttpVersion {get;set;}
		
		private Dictionary<string, Cookie> cookies = new Dictionary<string, Cookie>();
		public IEnumerable<Cookie> Cookies {
			get {
				foreach(string key in cookies.Keys) {
					yield return cookies[key];
				}
			}
		}
		
		public HttpResponse(StreamWriter writer)
		{
			this.SetProperty(HttpProperty.ContentType, "text/html");
			this.HttpStatus = HttpStatus.STATUS_200_OK;
			this.outputStream = new ResponseStream(writer.BaseStream, this);
			this.HttpVersion = HttpVersion.V1_1;
		}
		
		public string GetProperty(HttpProperty property) {
			return properties[property];
		}
		
		public void SetProperty(HttpProperty property, string value) {
			DontAllowContentLength(property);
			properties[property] = value;
		}
		
		public void RemoveProperty(HttpProperty property) {
			properties.Remove(property);
		}
		
		private void DontAllowContentLength(HttpProperty key) {
			if(key == HttpProperty.ContentLength) {
				throw new CannotSetContentLengthException();
			}
		}
		
		public void SetCookie(Cookie cookie) {
			cookies[cookie.Name] = cookie;
		}
		
		public void DeleteCookie(Cookie cookie) {
			cookies[cookie.Name] = cookie.Delete();
		}
		
		public void Redirect(string url) {
			this.outputStream.WriteLine("<html><head><meta http-equiv=\"Refresh\" content=\"0; url="+url+"\"></head></html>");
		}
	}
}